//
//  AddressListController.m
//  
//
//  Created by admin on 16/4/27.
//
//

#import "AddressListController.h"
#import "LoginViewController.h"

@interface AddressListController ()<UIWebViewDelegate>


@property (nonatomic,strong) UILabel *topTitle;

@property (nonatomic,strong) UIButton *topBackBtn;

@end

@implementation AddressListController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
        [self createTopView];
    
    
    _webViewUrl = [NSMutableString stringWithFormat:@"%@?sessionId=%@",url_web_Address,static_sessionId];
    
    _webViewUrl = [NSMutableString stringWithFormat:@"%@",[_webViewUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * _req = [NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl]];
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,64, kScreen_Width, kScreen_Height - 64)];
    _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
    [_webView loadRequest:_req];
    _webView.scrollView.bounces = NO;
    _webView.suppressesIncrementalRendering = NO;
    _webView.delegate = self;
    [_webView setBackgroundColor:[AppConfig colorWithHexString:@"#ececec"]];
    [self.view addSubview:_webView];
    
    
}

-(void)createTopView{
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 64)];
    topView.backgroundColor = RGB(249, 249, 249);
    [self.view addSubview:topView];
    
    _topTitle = [[UILabel alloc]initWithFrame:CGRectMake(kScreen_Width/2 - 60,20,120,44)];
    _topTitle.numberOfLines = 1;
    _topTitle.clipsToBounds = YES;
    _topTitle.layer.cornerRadius = 4;
    _topTitle.textAlignment = NSTextAlignmentCenter;
    _topTitle.font = [UIFont systemFontOfSize:15];
    _topTitle.textColor = RGBJ(44);
    _topTitle.text = @"我的地址";
    [topView addSubview:_topTitle];
    
    _topBackBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_topBackBtn setFont:[UIFont systemFontOfSize:15]];
    [_topBackBtn setBackgroundColor:[UIColor whiteColor]];
    [_topBackBtn setBackgroundImage:[UIImage imageNamed:@"xiangyou.png"] forState:UIControlStateNormal];
    [_topBackBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _topBackBtn.frame = CGRectMake(8,28,24,24);
    [_topBackBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:_topBackBtn];
    
}

-(void)backAction{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
                NSLog(@"回归主线程");
                [self.view resignFirstResponder];
                [self.navigationController popViewControllerAnimated:YES];
                //                   [self.navigationController popToRootViewControllerAnimated:YES];
                
            });
        });
    }
    NSLog(@"-------goBack---------");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -mark WebView
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"WebView erros is %@",error);
    if ([error code] == NSURLErrorCancelled) {
        return;
    }
    // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"error" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
}


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"====webViewDidFinishLoad");
    
    // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    
    //JS交互
        JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        context[@"JavaScriptInterface"] = self;
}

- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *urlStr = [[request URL] absoluteString];
    
    NSLog(@"urlStr = %@",urlStr);
    //http://www.zjtosj.com:8089/wap/detail/proId=ff80808158716e71015874f94027002a
    NSRange range = NSMakeRange(31, 6);
    
    //用边界截取起始位置为第四个，长度为5个长度
    
    NSString *aString = [urlStr substringWithRange:range];
    NSLog(@"%@",aString);
    
    if ([aString isEqualToString:@"detail"]) {
               return NO;
    }else{
        return YES;
    }
    
    
    
}

-(void)HNWebJSExportGotoLoginVC{
    [AppConfig removeUserInfo];
    
    [[EMClient sharedClient] logout:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    
    [self.navigationController pushViewController:loginVC animated:YES];
}

-(void)HNWebJSExportBack{
    
    
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
                NSLog(@"回归主线程");
                [self.view resignFirstResponder];
                [self.navigationController popViewControllerAnimated:YES];
            });
        });
    }
    NSLog(@"-------goBack---------");
}


@end
